package com.heima.common.autoconfig.template;

import com.heima.common.autoconfig.properties.Tess4jPreperties;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

public class Tess4jTemplate {

    private Tess4jPreperties tess4jPreperties;

    public Tess4jTemplate(Tess4jPreperties tess4jPreperties) {
        this.tess4jPreperties = tess4jPreperties;
    }

    public String doOCR(BufferedImage image) {

        try {
            //创建Tesseract对象
            ITesseract tesseract = new Tesseract();
            //设置字体库路径
            tesseract.setDatapath(tess4jPreperties.getDataPath());
            //中文识别
            tesseract.setLanguage(tess4jPreperties.getLanguage());
            //执行ocr识别
            String result = tesseract.doOCR(image);
            //替换回车和tal键  使结果为一行
            result = result.replaceAll("\\r|\\n", "-").replaceAll(" ", "");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public String doOCR(byte[] bytes) {

        try {
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            BufferedImage imageFile = ImageIO.read(in);

            return doOCR(imageFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
